package com.code.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.code.common.constant.CodeConst;
import com.code.user.model.RolePermissionDO;
import com.code.user.mapper.RolePermissionMapper;
import com.code.user.service.RolePermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色权限关联表 服务实现类
 * </p>
 *
 * @author Yan
 * @since 2023-04-24
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermissionDO> implements RolePermissionService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public List<Map<String, Object>> selectLinkRolePermission() {
        return this.baseMapper.selectLinkRolePermission();
    }

    @Override
    public Map<String, List<String>> pushCache(List<Map<String, Object>> rolePermissionDataList) {
        Map<String, List<String>> map = new TreeMap<>();
        Map<String, List<Map<String, Object>>> perUrlGroup = rolePermissionDataList.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(data -> (String) data.get("perUrl")));

        for (Map.Entry<String, List<Map<String, Object>>> entry : perUrlGroup.entrySet()) {
            if (CollectionUtils.isEmpty(entry.getValue())) {
                continue;
            }

            List<String> roleList = entry.getValue().stream().filter(data -> StrUtil.isNotEmpty((String) data.get("roleName"))).map(data -> (String) data.get("roleName")).collect(Collectors.toList());
            map.put(entry.getKey(), roleList);
        }

        redisTemplate.opsForHash().putAll(CodeConst.ROLE_PERMISSION_HASH_KEY, map);
        return map;
    }
}
